package threadLock.threadBasics.threadLocal;

/**
 * threadLocal 在每一个线程的副本这种 生成一个副本 数据格式是一个map类型  k 当前线程 v 线程set值
 * 使用结束之后需要删除 否则会线程溢出
 * 不支持继承
 * InheritableThreadLocal 可以让ThreadLocal支持继承
 * 在子线程中重新开启一个threadLocals变量 复制父类的值  删除的时候需要父 子线程都删除 否则会造成溢出
 */
public class ThreadLocalTest {

    static ThreadLocal<String> localVariableInheritable = new InheritableThreadLocal<>();

    static ThreadLocal<String> localVariable = new ThreadLocal<>();

    static void print(String str){
        System.out.println(str + ":" + localVariable.get());
//        localVariable.remove();
    }

    public static void main(String[] args) throws InterruptedException {
        Thread threadOne = new Thread(() -> {
            localVariable.set("threadOne set local Variable");
            print("threadOne");
            System.out.println("threadOne remove after"+":"+localVariable.get());
        }, "threadOne");

        Thread threadTwo = new Thread(() -> {
            localVariable.set("threadTwo set local Variable");
            print("threadTwo");
            System.out.println("threadTwo remove after"+":"+localVariable.get());
        }, "threadTwo");
//        threadOne.start();
//        threadTwo.start();

        localVariableInheritable.set("main set value");
        Thread threadSon = new Thread(() -> {
            System.out.println("threadSon: "+localVariableInheritable.get());
            //子线程删除 不影响主线程读取
            localVariableInheritable.remove();
            System.out.println();
        }, "threadSon");
        threadSon.start();
        Thread.sleep(1000);
        System.out.println("main: "+localVariableInheritable.get());
        localVariableInheritable.remove();

        localVariable.set("main set value");
        Thread threads = new Thread(() -> {
            System.out.println("threads: "+localVariable.get());
        }, "threads");
        threads.start();
        System.out.println("main: "+localVariable.get());
        localVariable.remove();
    }
}
